package com.wk.paradise.redis.utils;

import com.wk.paradise.redis.constants.Constants;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtils {

    static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    /**
     * post请求（用于请求json格式的参数）
     * @param url
     * @param params
     * @return
     */
    public static String sendPost(String url, String params) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", Constants.CONTEXT_TYPE);
        httpPost.setHeader("Content-Type", Constants.CONTEXT_TYPE);
        StringEntity entity = new StringEntity(params,Constants.CHAR_SET);
        entity.setContentEncoding(Constants.CHAR_SET);
        entity.setContentType(Constants.CONTEXT_TYPE);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                result = jsonString;
            } else {
                logger.error("请求返回:{}({})", state, url);
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("response关闭时出错,{}", e.getMessage(), e);
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("httpclient关闭时出错,{}", e.getMessage(), e);
            }
        }
        return result;
    }

    /**
     * post请求（用于请求json格式的参数）
     * @param url
     * @return
     */
    public static String sendGet(String url) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpclient.execute(httpGet);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                result = jsonString;
            } else {
                logger.error("请求返回:{}({})", state, url);
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("response关闭时出错,{}", e.getMessage(), e);
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("httpclient关闭时出错,{}", e.getMessage(), e);
            }
        }
        return result;
    }

    public static String sendPostWithUrlConllection(String getUrl,String params){

        String result = "";
        try {
            URL url = new URL(getUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");//设置参数类型是json格式
            connection.connect();

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(params);
            writer.close();

            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                InputStream inputStream = connection.getInputStream();
                result = is2String(inputStream);//将流转换为字符串。
            }
        } catch (Exception e) {
            logger.error("请求发生错误：{}",e.getMessage(),e);
        }
        return result;
    }

    private static String is2String(InputStream inputStream) {

        StringBuilder stringBuilder = new StringBuilder();
        if(inputStream !=null){
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String string = "";
                while ((string = bufferedReader.readLine()) != null){
                    stringBuilder.append(string);
                }
            }catch (Exception e){
                logger.error("流转换失败：{}",e.getMessage(),e);
            }
        }

        return stringBuilder.toString();
    }

    /**
     * 非json参数方式POST提交
     *
     * @param uri
     * @param param
     * @return
     */
    public static String sendPost(String uri,  Map<String, Object> param) {
        String result = "";
        CloseableHttpClient httpclient = null;
        try {
            List<NameValuePair> params = new ArrayList<>();
            if(param != null && !param.isEmpty()) {
                param.forEach((k,v) -> params.add(new BasicNameValuePair(k, v.toString())));
            }
            httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(uri);
            httpPost.addHeader("Content-Type", Constants.FORM_CONTEXT_TYPE); // 添加请求头
            httpPost.setEntity(new UrlEncodedFormEntity(params, Constants.CHAR_SET));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instreams = entity.getContent();
                result = is2String(instreams);
            }
        } catch (Exception e) {
            e.getMessage();
        }finally {
            if(httpclient != null){
                IOUtils.closeQuietly(httpclient);
            }
        }
        return result;
    }

}
